/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.facedoor.modular.memberdevice.controller;

import cn.hutool.core.bean.BeanUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.DataScope;
import vip.xiaonuo.core.annotion.Permission;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.core.util.PoiUtil;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.param.LockerPersonImportBean;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.modular.memberdevice.mapper.MemberDeviceMapper;
import vip.xiaonuo.facedoor.modular.memberdevice.param.LockerMemberSaveParam;
import vip.xiaonuo.facedoor.modular.memberdevice.param.MemberAdminSaveParam;
import vip.xiaonuo.facedoor.modular.memberdevice.service.MemberDeviceService;
import vip.xiaonuo.facedoor.modular.memberdevice.vo.LockerMemberDeviceVO;
import vip.xiaonuo.facedoor.modular.memberdevice.vo.MemberDeviceVO;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 人员设备关系表控制器
 *
 * @author 胡鹏达
 * @date 2022-07-13 09:03:01
 */
@RestController
public class MemberDeviceController {

    @Resource
    private MemberDeviceService memberDeviceService;

    @Resource
    private DeviceBaseService deviceBaseService;

    @Resource
    private MemberDeviceMapper memberDeviceMapper;

    @GetMapping("/memberDevice/page")
    @BusinessLog(title = "设备人员权限_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    @DataScope
    public ResponseData page(@RequestParam(required = false) Long orgId,
                             @RequestParam(name = "name", required = false) String name,
                             @RequestParam(name = "jobNum", required = false) String jobNum,
                             @RequestParam(name = "deviceId", required = false) Long deviceId,
                             @RequestParam(name = "memberId", required = false) Long memberId,
                             @RequestParam(name = "memberStatus", required = false) Integer memberStatus) {
        return new SuccessResponseData(memberDeviceService.selectPage(orgId, name, jobNum, deviceId, memberId, memberStatus));
    }

    @GetMapping("/memberDevice/selectLockerMember")
    @BusinessLog(title = "寄存柜设备人员权限_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData selectLockerMember(@RequestParam Long deviceId) {
        Map<String, Object> result = new HashMap<>();
        List<LockerMemberDeviceVO> resultVos = new ArrayList<>();
        List<LockerMemberDeviceVO> lockerMemberDeviceVOS = memberDeviceService.selectLockerMember(deviceId);
        for (LockerMemberDeviceVO lockerMemberDeviceVO : lockerMemberDeviceVOS) {
            if (StringUtils.isNotBlank(lockerMemberDeviceVO.getLockerData())) {
                String[] split = lockerMemberDeviceVO.getLockerData().split(",");
                for (String lock : split) {
                    LockerMemberDeviceVO deviceVO = new LockerMemberDeviceVO();
                    BeanUtil.copyProperties(lockerMemberDeviceVO, deviceVO);
                    deviceVO.setLockerData(lock);
                    resultVos.add(deviceVO);
                }
            }
        }
        Map<String, LockerMemberDeviceVO> collect = resultVos.stream().filter(x -> StringUtils.isNotBlank(x.getLockerData())).collect(Collectors.toMap(LockerMemberDeviceVO::getLockerData, Function.identity()));
        result.put("results", collect);
        return new SuccessResponseData(result);
    }


    @PostMapping("/memberDevice/saveOrUpdateLockerMember")
    @BusinessLog(title = "寄存柜设备人员权限_新增", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData saveOrUpdateLockerMember(@RequestBody LockerMemberSaveParam deviceVO) {
        memberDeviceService.saveLockerMember(deviceVO);
        return new SuccessResponseData();
    }


    @GetMapping("/memberDevice/delete")
    @BusinessLog(title = "设备人员_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    @Permission
    public ResponseData delete(Long id) {
        try {
            memberDeviceService.delete(id);
        } catch (Exception e) {
            throw new ServiceException(500, "发生错误" + ExceptionUtils.getMessage(e));
        }
        return new SuccessResponseData();
    }

    @GetMapping("/memberDevice/sync")
    @BusinessLog(title = "设备人员_重新同步", opType = LogAnnotionOpTypeEnum.OTHER)
    public ResponseData sync(Long id) {
        try {
            memberDeviceService.sync(id);
        } catch (Exception e) {
            throw new ServiceException(500, "发生错误" + ExceptionUtils.getMessage(e));
        }
        return new SuccessResponseData();
    }


    @GetMapping("/memberDevice/onKeySync")
    @BusinessLog(title = "设备人员_一键同步", opType = LogAnnotionOpTypeEnum.OTHER)
    public ResponseData onKeySync() {
        try {
            memberDeviceService.onKeySync();
        } catch (Exception e) {
            throw new ServiceException(500, "发生错误" + ExceptionUtils.getMessage(e));
        }
        return new SuccessResponseData();
    }

    @GetMapping("/memberDevice/detail")
    @BusinessLog(title = "设备人员_详情", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData detail(Long id) {
        return ResponseData.success(memberDeviceService.getById(id));
    }


    @GetMapping("/memberDevice/adminList")
    @BusinessLog(title = "设备管理员权限_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    @DataScope
    public ResponseData listAdminUser(@RequestParam(name = "deviceId", required = true) Long deviceId,
                                      @RequestParam(name = "adminUser", required = false) Boolean adminUser
    ) {
        return new SuccessResponseData(memberDeviceService.listAdminUser(adminUser, deviceId));
    }


    @GetMapping("/memberDevice/LockerMemberExportTemplate")
    @BusinessLog(title = "寄存柜_模板导出", opType = LogAnnotionOpTypeEnum.EXPORT)
    public void lockerMemberExport() {
        List<LockerPersonImportBean> lockerPersonImportBeans = new ArrayList<>();
        PoiUtil.exportExcelWithStream("寄存柜人员模板.xls", LockerPersonImportBean.class, lockerPersonImportBeans);
    }


    @GetMapping("/memberDevice/LockerMemberExport")
    @BusinessLog(title = "寄存柜_导出", opType = LogAnnotionOpTypeEnum.EXPORT)
    public void lockerMemberExport(@RequestParam(name = "deviceId", required = false) Long deviceId,
                                   @RequestParam(name = "adminUser", required = false) Boolean adminUser) {
        List<MemberDeviceVO> memberDeviceVOS = memberDeviceMapper.selectAdminUserList(adminUser, deviceId);
        PoiUtil.exportExcelWithStream("寄存柜人员.xls", MemberDeviceVO.class, memberDeviceVOS);
    }


    @PostMapping("/memberDevice/adminSave")
    @BusinessLog(title = "设备管理员_保存", opType = LogAnnotionOpTypeEnum.QUERY)
    @DataScope
    public ResponseData deviceAdminSave(@RequestBody MemberAdminSaveParam param) {
        memberDeviceService.deviceAdminSave(param);
        return new SuccessResponseData();
    }
}